const CryptoJS = require("crypto-js");
const { isString } = require("./is");
const KEY = process.env.NODE_ENV + "_" + process.env.SECRET;

/**
 * * 加密
 * @param data { string }
 * @returns
 */
const cryptoEncode = (data) => {
  if (!isString(data)) return "";
  // 加密
  const encryptedData = CryptoJS.AES.encrypt(data, KEY, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).toString();
  return encryptedData;
};

/**
 * * 解密
 * @param data { string }
 * @returns
 */
const cryptoDecode = (data) => {
  if (!isString(data)) return "";
  // 解密
  const decryptedData = CryptoJS.AES.decrypt(data, KEY, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return decryptedData.toString(CryptoJS.enc.Utf8);
};

module.exports = {
  cryptoDecode,
  cryptoEncode,
};
